function [elem node] = uniformrefine(elem,node,n)
% UNIFORMREFINE refines the current triangulation by dividing
%   each triangle into four similar triangles
%
% USAGE
%    [mesh] = uniformrefine(mesh)
%
% Input:
%     mesh:  current mesh
% 
% Output: 
%     mesh:  new mesh after refinement
%


%ndimension=4;

%fprintf('\n Maping solution: current level: level %g  to level %g ...',old_level,new_level);
%--------------------------------------------------------------------------
% Construct data structure
%--------------------------------------------------------------------------
for i=1:n

edge = [elem(:,[1,2]); elem(:,[1,3]); elem(:,[2,3])];
edge = unique(sort(edge,2),'rows');
N = size(node,1); NT = size(elem,1); NE = size(edge,1);
d2p = sparse(edge(:,[1,2]),edge(:,[2,1]),[1:NE,1:NE],N,N);

%--------------------------------------------------------------------------
% New nodes from the mid points of each edge
%--------------------------------------------------------------------------


    

newnode = (node(edge(:,1),:)+node(edge(:,2),:))/2; 
node = [node; newnode]; 

marker = N+1:N+NE; 

%--------------------------------------------------------------------------
% refine each triangle into four triangles
%     3
%    / \
%   6 - 5
%  / \ / \
% 1 - 4 - 2
%--------------------------------------------------------------------------
for t=1:NT
    p(1:3) = elem(t,[1 2 3]); 
    p(4) = marker(d2p(elem(t,1),elem(t,2)));
    p(5) = marker(d2p(elem(t,2),elem(t,3)));
    p(6) = marker(d2p(elem(t,3),elem(t,1)));
    elem(t,[1 2 3]) = [p(1) p(4) p(6)];
   elem(size(elem,1)+1,[1 2 3]) = [p(4) p(2) p(5)];
    elem(size(elem,1)+1,[1 2 3]) = [p(6) p(5) p(3)];
   elem(size(elem,1)+1,[1 2 3]) = [p(4) p(5) p(6)];
end


end









%-------------------------------------------